package com.mathmodeling.controller;

import com.mathmodeling.dto.ApiResponse;
import com.mathmodeling.dto.LoginRequest;
import com.mathmodeling.dto.LoginResponse;
import com.mathmodeling.entity.User;
import com.mathmodeling.repository.UserRepository;
import com.mathmodeling.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.UUID;

@RestController
@RequestMapping("/test")
public class TestController {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder passwordEncoder;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @GetMapping("/login-test")
    public ApiResponse<String> testLoginEndpoint() {
        return ApiResponse.success("登录接口测试端点可用");
    }
    
    @PostMapping("/create-test-user")
    public ApiResponse<String> createTestUser(@RequestParam String username, 
                                            @RequestParam String password, 
                                            @RequestParam String role) {
        try {
            // 检查用户名是否已存在
            if (userRepository.existsByUsername(username)) {
                return ApiResponse.error(400, "用户名已存在");
            }
            
            // 创建测试用户
            User user = new User();
            user.setId(UUID.randomUUID().toString());
            user.setUsername(username);
            user.setPassword(passwordEncoder.encode(password));
            user.setRole(role);
            user.setCreatedAt(LocalDateTime.now());
            
            userRepository.save(user);
            
            return ApiResponse.success("测试用户创建成功: " + username + "/" + password + " (角色: " + role + ")");
            
        } catch (Exception e) {
            return ApiResponse.error(500, "创建测试用户失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/users")
    public ApiResponse<String> listUsers() {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("当前系统中的用户:\n");
            
            userRepository.findAll().forEach(user -> {
                sb.append("- 用户名: ").append(user.getUsername())
                  .append(", 角色: ").append(user.getRole())
                  .append(", ID: ").append(user.getId())
                  .append("\n");
            });
            
            return ApiResponse.success(sb.toString());
            
        } catch (Exception e) {
            return ApiResponse.error(500, "获取用户列表失败: " + e.getMessage());
        }
    }
} 